/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Frank
 */
public class VertaalServer {
    
    private ServerSocket serversocket;
    private Socket clientsocket;
    
    public VertaalServer() {
        
        this.makeListener();
        
        try {
            
           clientsocket = serversocket.accept();
           
        } catch(IOException e) {
            System.out.println(e);
            System.exit(1);
        }
        
        this.handleRequests();
        
    }
    
    private void handleRequests() {
        
        String input;
        String output;
        Protocol protocol = new Protocol();
        
        try {
            
            // Luister de verbinding af dmv deze readers
            PrintWriter uit = new PrintWriter(clientsocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
            
            output = protocol.vertaal(null);
            
            uit.println(output);

            // Verwerk the input van de user dmv protocol
            while ((input = in.readLine()) != null) {
                
                output = protocol.vertaal(input);
                
                uit.println(output);
                if (output.equals("Bye.")) {
                        break;
                }
                
            }
            
            // Verbinding weer sluiten
            uit.close();
            in.close();
            clientsocket.close();
            serversocket.close();
            
            
        } catch(IOException e) {
            System.out.println(e);
        }
        
    }
    
    private void makeListener() {
        
        try {
            
            this.serversocket = new ServerSocket(Settings.port);
            System.out.println("Wachten op invoer");
            
        } catch(IOException e) {
            System.out.println(e);
        }
        
    }
    
}
